<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片上传</title>
</head>
<body>
    <form action="imageUpload" method="post" enctype="multipart/form-data">
        <input type="file" name="fileName" id="filename" accept="image/png, image/jpeg, image/jpg" onchange="onLoadImage()">
        <input type="button" id="submitBtn" onclick="checkSubmit()" value="上传"/>
    </form>
    <div id="onLoadImage"></div>
</body>
<script src="/webjars/jquery/3.3.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script type="text/javascript">

    //检查图片
    function checkImage() {
        var fileName=$("#filename").val();
        fileName=fileName.replace("C:\\fakepath\\","");
        var flag=true;
        if(fileName==""){
            flag=false;
            alert("请选择图片");
        }
        else{
            var size = $("#filename")[0].files[0].size;
            if(size/1000>100){
                flag=false;
                alert("图片大小不能超过100KB");
            }
        }
        if(!flag)
            $("#filename").val("");
        return flag;
    }

    //预览图片
    function onLoadImage() {
        if(checkImage()){
            var file=$('#filename').get(0).files[0];
            var reader = new FileReader();
            //将文件以Data URL形式读入页面
            reader.readAsDataURL(file);
            reader.onload=function(e){
                //显示文件
                $("#onLoadImage").html('<img src="' + this.result +'" alt="" />');
            }
        }

    }

    //上传图片
    function checkSubmit() {
        if(checkImage())
            $("#submitBtn").attr('type','submit');
        else
            $("#submitBtn").attr('type','button');
    }
</script>
</html>